package com.hex.tcpproxy.process;

/**
 * @author: [wujie]
 * @createTime: [2019/10/9 15:13]
 * @description:
 */
public class DataExplain {
    private byte[] data;
    private String cmd;
    private byte[] para;
    private byte[] realData;

    public DataExplain(String cmd, byte[] para, byte[] realData) {
        if (realData == null) {
            realData = new byte[1];
        }
        this.cmd = cmd;
        this.para = para;
        this.realData = realData;
        byte[] cmdBytes = cmd.getBytes();
        int cmdLen = cmdBytes.length;
        int paraLen = para.length;
        int totalLen = cmdLen + paraLen + realData.length;
        this.data = new byte[totalLen + 2];
        this.data[0] = (byte) cmdLen;
        this.data[1] = (byte) paraLen;
        System.arraycopy(cmdBytes, 0, this.data, 2, cmdLen);
        System.arraycopy(para, 0, this.data, cmdLen + 2, paraLen);
        System.arraycopy(realData, 0, this.data, cmdLen + paraLen + 2, realData.length);
    }


    public DataExplain(byte[] data) {
        this.data = data;
        int cmdLen = data[0];
        int paraLen = data[1];
        byte[] cmdBytes = new byte[cmdLen];
        this.para = new byte[paraLen];
        this.realData = new byte[data.length - cmdLen - paraLen - 2];
        System.arraycopy(data, 2, cmdBytes, 0, cmdLen);
        System.arraycopy(data, 2 + cmdLen, para, 0, paraLen);
        System.arraycopy(data, 2 + cmdLen + paraLen, realData, 0, realData.length);
        this.cmd = new String(cmdBytes);
    }

    public static byte[] getAddressBytes(String address) {
        String[] split = address.split(":");
        String[] ipStrs = split[0].split("\\.");
        byte[] addressBytes = new byte[5];
        addressBytes[0] = (byte) (Integer.parseInt(ipStrs[0]) - 128);
        addressBytes[1] = (byte) (Integer.parseInt(ipStrs[1]) - 128);
        addressBytes[2] = (byte) (Integer.parseInt(ipStrs[2]) - 128);
        addressBytes[3] = (byte) (Integer.parseInt(ipStrs[3]) - 128);
        addressBytes[4] = (byte) (Integer.parseInt(split[1]) - 128);
        return addressBytes;
    }

    public static String getAddressString(byte[] addressBytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            sb.append(128 + addressBytes[i]).append(".");
        }
        sb.deleteCharAt(sb.lastIndexOf("."));
        sb.append(":");
        sb.append(128 + addressBytes[4]);
        return sb.toString();
    }


    public byte[] getData() {
        return data;
    }

    public String getCmd() {
        return cmd;
    }

    public byte[] getPara() {
        return para;
    }

    public byte[] getRealData() {
        return realData;
    }

}
